package com.ss.demo.springbootdemo.ioc;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 作者: MrZhangJR
 * 时间: 2021/11/8 14:35
 * 描述:  ioc:  从properties中读取
 *              1. 采集元数据 -> 源码编写
 *              2. 实例化, 放入到ioc容器.
 *              3. 完成依赖注入.
 */
public class BeanFactory {

    private static Properties properties;

    private static Map<String, Object> iocContainer = new HashMap<>();

    static {
        properties = new Properties();
        try {
            properties.load(BeanFactory.class.getClassLoader().getResourceAsStream("factory.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object getBean(String key) {
        // 多线程环境下的单例模式
        if (!iocContainer.containsKey(key)) {
            synchronized (BeanFactory.class) {
                if (!iocContainer.containsKey(key)) {
                    String classpath = properties.getProperty(key);
                    try {
                        Class<?> aClass = Class.forName(classpath);
                        Object o = aClass.newInstance();
                        iocContainer.put(key, o);
                        return o;
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return iocContainer.get(key);
    }

}
